#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "nvs_flash.h"
#include "led.h"
#include "tftspi.h"
#include "my_adc.h"
#include "usart.h"
#include "line_chart.h"

uint32_t adc_data;
uint32_t vout_mv;
uint16_t vout_mv1;        /* 低16位示例 */

static uint8_t u32_to_dec(uint32_t value, char *buf)
{
    char tmp[11];
    uint8_t i = 0;
    if (value == 0) { buf[0] = '0'; buf[1] = '\0'; return 1; }
    while (value) { tmp[i++] = (char)('0' + (value % 10)); value /= 10; }
    uint8_t len = i, j = 0;
    while (i--) buf[j++] = tmp[i];
    buf[j] = '\0';
    return len;
}

void app_main(void)
{
    esp_err_t ret;
    uint8_t adc_buf[8];

    ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND)
    {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }

    led_init();
    IO_init();
    OLED_init();
    OLED_clear();
    adc_init();
    usart_init(115200);
    linechart_init();

    while (1)
    {
        adc_data  = adc_get_result_average(ADC_ADCX_CHY, 10);
        vout_mv   = adc_data * 3300 / 4096;
        vout_mv1  = (uint16_t)(vout_mv & 0xFFFFu);   /* 仅保留低16位 */

        /* 显示中文（固定位置，不闪烁） */
        display_char32_32(5, 200, RED, china_char[0]);
        display_char32_32(40, 200, RED, china_char[1]);
        display_char32_32(75, 200, RED, china_char[2]);
        display_char32_32(110, 200, RED, china_char[3]);
        display_char32_32(145, 200, RED, china_char[4]);
        display_char32_32(180, 200, RED, china_char[5]);
        display_char32_32(215, 200, RED, china_char[6]);

        /* 无闪烁更新电压值 */
        lcd_print_u16_mv(150, 240, vout_mv1, GREEN);

        linechart_update(vout_mv1);

        /* 串口数据上传 */
        adc_buf[0] = adc_data & 0xFF;
        adc_buf[1] = (adc_data >> 8) & 0xFF;
        adc_buf[2] = (adc_data >> 16) & 0xFF;
        adc_buf[3] = (adc_data >> 24) & 0xFF;
        adc_buf[4] = 0;
        adc_buf[5] = 0;
        adc_buf[6] = vout_mv & 0xFF;
        adc_buf[7] = (vout_mv >> 8) & 0xFF;
        uart_write_bytes(UART_NUM_0, adc_buf, sizeof(adc_buf));
        vTaskDelay(1000);
    }
}
